package com.taxi.driver.common;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.net.http.SslError;
import android.os.Build;
import android.os.Handler;
import android.support.v4.app.ActivityCompat;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.LinearLayout;
import android.widget.ProgressBar;

import com.taxi.driver.R;

/**
 * Created by Administrator on 2017/4/7.
 */
public class BaseWebView extends BaseActivity {

    private static final String TAG = BaseWebView.class.getSimpleName();

    public static final String URL_INTENT_KEY = "url";
    public static final String TITLE_INTENT_KEY = "title";
    public static final String HTML_KEY = "html";

    protected LinearLayout loadErrorLayout;
    protected WebView webView;
    protected ProgressBar webviewProgress;
    protected static final String UA = "qianxx";

    protected String url;
    protected String html;

    private Handler hlr;

    protected void setHandler(Handler hlr) {
        this.hlr = hlr;
    }

    protected void callback() {
        if (hlr != null) {
            hlr.sendEmptyMessage(0);
        }
    }

    protected void initWebView() {
        initWebView(null);
    }

    protected void initWebView(final View parent) {

        if (parent != null) {
            webView = (WebView) parent.findViewById(R.id.web_view);
            loadErrorLayout = (LinearLayout) parent
                    .findViewById(R.id.load_error_layout);
            webviewProgress = (ProgressBar) parent
                    .findViewById(R.id.webview_progress);
        } else {
            webView = (WebView) findViewById(R.id.web_view);
            loadErrorLayout = (LinearLayout) findViewById(R.id.load_error_layout);
            webviewProgress = (ProgressBar) findViewById(R.id.webview_progress);
        }

        loadErrorLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                initWebView(parent);
                loadWebData();
            }
        });

//        setJavaScriptEnabled(true);//让WebView支持JavaScript
//        setUserAgentString(); //设置浏览器标识
//        setDomStorageEnabled(true);//启用H5 DOM API （默认false）
//        setDatabaseEnabled(true);//启用数据库api（默认false）可结合 setDatabasePath 设置路径
//        setCacheMode(WebSettings.LOAD_DEFAULT)//设置缓存模式
//        setAppCacheEnabled(true);//启用应用缓存（默认false）可结合 setAppCachePath 设置缓存路径
//        setAppCacheMaxSize()//已过时，高版本API上，系统会自行分配
//        setPluginsEnabled(true);  //设置插件支持
//        setRenderPriority(RenderPriority.HIGH);  //提高渲染的优先级
//        setUseWideViewPort(true);  //将图片调整到适合webview的大小
//        setLoadWithOverviewMode(true); // 缩放至屏幕的大小
//        setSupportZoom(true);  //支持缩放，默认为true
//        setBuiltInZoomControls(true); //设置内置的缩放控件（若SupportZoom为false，该设置项无效）
//        setDisplayZoomControls(false); //隐藏原生的缩放控件
//        setLayoutAlgorithm(LayoutAlgorithm.SINGLE_COLUMN); //支持内容重新布局
//        supportMultipleWindows();  //支持多窗口
//        setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);  //关闭webview中缓存
//        setAllowFileAccess(true);  //设置可以访问文件
//        setNeedInitialFocus(true); //当webview调用requestFocus时为webview设置节点
//        setJavaScriptCanOpenWindowsAutomatically(true); //支持通过JS打开新窗口
//        setLoadsImagesAutomatically(true);  //自动加载图片
//        setDefaultTextEncodingName("utf-8");//设置编码格式
//        setInitialScale(); //设置缩放等级

        String ua = webView.getSettings().getUserAgentString();

        if (!TextUtils.isEmpty(ua)) {
            ua += UA;
        } else {
            ua = UA;
        }

        webView.getSettings().setUserAgentString(ua);
        webView.getSettings().setJavaScriptEnabled(true);
        webView.getSettings().setSupportZoom(true);
        webView.getSettings().setBuiltInZoomControls(false);
        webView.getSettings().setDefaultTextEncodingName("utf-8");
        webView.setWebChromeClient(webChromeClient);
        webView.setWebViewClient(webClient);

        webView.setVerticalScrollBarEnabled(false);
        webView.setVerticalScrollbarOverlay(false);
        webView.setHorizontalScrollBarEnabled(false);
        webView.setHorizontalScrollbarOverlay(false);

        //LOAD_CACHE_ONLY: 不使用网络，只读取本地缓存数据
        //LOAD_DEFAULT: （默认）根据cache-control决定是否从网络上取数据。
        //LOAD_NO_CACHE: 不使用缓存，只从网络获取数据.
        //LOAD_CACHE_ELSE_NETWORK，只要本地有，无论是否过期，或者no-cache，都使用缓存中的数据。
        webView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);

        // 网页自动适配屏幕大小
        webView.getSettings().setUseWideViewPort(true);
        webView.getSettings().setLoadWithOverviewMode(true);
        webView.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        webView.getSettings().setDomStorageEnabled(true);

        //在Android 5.0上 Webview 默认不允许加载 Http 与 Https 混合内容
        //MIXED_CONTENT_ALWAYS_ALLOW：允许从任何来源加载内容，即使起源是不安全的；
        //MIXED_CONTENT_NEVER_ALLOW：不允许Https加载Http的内容，即不允许从安全的起源去加载一个不安全的资源；
        //MIXED_CONTENT_COMPATIBILITY_MODE：当涉及到混合式内容时，WebView 会尝试去兼容最新Web浏览器的风格。
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            webView.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_COMPATIBILITY_MODE);
        }

        DisplayMetrics metrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(metrics);
        int mDensity = metrics.densityDpi;

        if (mDensity == 120) {
            webView.getSettings().setDefaultZoom(WebSettings.ZoomDensity.CLOSE);
        } else if (mDensity == 160) {
            webView.getSettings().setDefaultZoom(WebSettings.ZoomDensity.MEDIUM);
        } else if (mDensity == 240) {
            webView.getSettings().setDefaultZoom(WebSettings.ZoomDensity.FAR);
        }

    }

    protected void loadWebData() {
        if (!TextUtils.isEmpty(url)) {
            loadErrorLayout.setVisibility(View.GONE);
            loadWeb(url);
        }
        if (!TextUtils.isEmpty(html)) {
            loadErrorLayout.setVisibility(View.GONE);
            loadWebByDataWithBaseURL(html);
        }
        if (TextUtils.isEmpty(url) && TextUtils.isEmpty(html)) {
            loadWebByDataWithBaseURL("<html></html>");
        }
    }

    protected void loadWeb(String url) {
        if (webView != null && !TextUtils.isEmpty(url)) {
            synCookies(this, url);
            webView.loadUrl(url);
        }
    }

    protected void loadWebByDataWithBaseURL(String data) {
        webView.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        webView.getSettings().setTextSize(WebSettings.TextSize.LARGEST);
        webView.setInitialScale(100);
        webView.getSettings().setSupportZoom(true);
        if (webView != null && !TextUtils.isEmpty(data)) {
            webView.loadDataWithBaseURL(null, data, "text/html", "utf-8", null);
        }
    }

    protected void synCookies(Context context, String url) {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
            CookieSyncManager.createInstance(context);
        }
        CookieManager cookieManager = CookieManager.getInstance();
        cookieManager.setAcceptCookie(true);
    }

    protected WebChromeClient webChromeClient = new WebChromeClient() {

        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            if (newProgress != 100) {
                webviewProgress.setProgress(newProgress);
            }
            super.onProgressChanged(view, newProgress);
        }

        @Override
        public void onReceivedTitle(WebView view, String title) {
            if (mRefreshTitleListener != null) {
                mRefreshTitleListener.onRefreshTitle(title);
            }
            super.onReceivedTitle(view, title);
        }
    };

    protected WebViewClient webClient = new WebViewClient() {

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            onWebPageFinished(view, url);
            webviewProgress.setVisibility(View.GONE);
            webView.getSettings().setLoadsImagesAutomatically(true);
            callback();
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            webviewProgress.setVisibility(View.VISIBLE);
            webView.getSettings().setLoadsImagesAutomatically(false);
            super.onPageStarted(view, url, favicon);
        }

        /**
         * 判断是否是需要过滤的url,是的话,true 表示不处理
         */
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            if (url.endsWith(".apk")) {   //下载apk
                Uri uri = Uri.parse(url);
                Intent viewIntent = new Intent(Intent.ACTION_VIEW, uri);
                startActivity(viewIntent);
                return true;
            }
            if (url.startsWith(WebView.SCHEME_TEL)) {  //拨打电话  "tel:"
                Uri uri = Uri.parse(url);
                Intent intent = new Intent(Intent.ACTION_DIAL, uri);
                startActivity(intent);
                //Android6.0以后的动态获取打电话权限
                if (ActivityCompat.checkSelfPermission(BaseWebView.this, Manifest.permission.CALL_PHONE) == PackageManager.PERMISSION_GRANTED) {
                    startActivity(intent);
                    //这个超连接,java已经处理了，webview不要处理
                    return true;
                } else {
                    //申请权限
                    ActivityCompat.requestPermissions(BaseWebView.this, new String[]{Manifest.permission.CALL_PHONE}, 1);
                    return true;
                }
            }
            if (url.startsWith("sms:") || url.startsWith("smsto:")) {  //发送短信
                Uri uri = Uri.parse(url);
                Intent intent = new Intent(Intent.ACTION_SENDTO, uri);
                startActivity(intent);
                return true;
            }
            if (url.startsWith(WebView.SCHEME_MAILTO)) {    //发送邮件  "mailto:"
                Uri uri = Uri.parse(url);
                Intent intent = new Intent(Intent.ACTION_SENDTO, uri);
                startActivity(intent);
                return true;
            }
            if (url.startsWith(WebView.SCHEME_GEO)) {    //位置处理  "geo:"
                Uri uri = Uri.parse(url);
                Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                startActivity(intent);
                return true;
            }

            BaseWebView.this.shouldOverrideUrlLoading(view, url);
            webView.loadUrl(url);// 当打开新链接时，使用当前的 WebView，不会使用系统其他浏览器
            return true;
        }

        /**
         * API 24以后改用 shouldOverrideUrlLoading(WebView, WebResourceRequest)
         * 代替shouldOverrideUrlLoading (WebView view, String url)，为了兼容不同API版本，最好同时重写上述两种方法
         * @param view
         * @param request
         * @return
         */
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                if (request.getUrl().toString().endsWith(".apk")) {   //下载apk
                    Uri uri = Uri.parse(request.getUrl().toString());
                    Intent viewIntent = new Intent(Intent.ACTION_VIEW, uri);
                    startActivity(viewIntent);
                    return true;
                }
                if (request.getUrl().toString().startsWith(WebView.SCHEME_TEL)) {  //拨打电话  "tel:"
                    Uri uri = Uri.parse(request.getUrl().toString());
                    Intent intent = new Intent(Intent.ACTION_DIAL, uri);
                    startActivity(intent);
                    //Android6.0以后的动态获取打电话权限
                    if (ActivityCompat.checkSelfPermission(BaseWebView.this, Manifest.permission.CALL_PHONE) == PackageManager.PERMISSION_GRANTED) {
                        startActivity(intent);
                        //这个超连接,java已经处理了，webview不要处理
                        return true;
                    } else {
                        //申请权限
                        ActivityCompat.requestPermissions(BaseWebView.this, new String[]{Manifest.permission.CALL_PHONE}, 1);
                        return true;
                    }
                }
                if (request.getUrl().toString().startsWith("sms:") || request.getUrl().toString().startsWith("smsto:")) {  //发送短信
                    Uri uri = Uri.parse(request.getUrl().toString());
                    Intent intent = new Intent(Intent.ACTION_SENDTO, uri);
                    startActivity(intent);
                    return true;
                }
                if (request.getUrl().toString().startsWith(WebView.SCHEME_MAILTO)) {    //发送邮件  "mailto:"
                    Uri uri = Uri.parse(request.getUrl().toString());
                    Intent intent = new Intent(Intent.ACTION_SENDTO, uri);
                    startActivity(intent);
                    return true;
                }
                if (url.startsWith(WebView.SCHEME_GEO)) {    //位置处理  "geo:"
                    Uri uri = Uri.parse(request.getUrl().toString());
                    Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                    startActivity(intent);
                    return true;
                }

                BaseWebView.this.shouldOverrideUrlLoading(view, request.getUrl().toString());
                webView.loadUrl(request.getUrl().toString());// 当打开新链接时，使用当前的 WebView，不会使用系统其他浏览器
            }
            return true;
        }

        @Override
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
            loadWebByDataWithBaseURL("<html></html>");
            loadErrorLayout.setVisibility(View.VISIBLE);
        }

        /**
         * API 23之前回调onReceivedError(WebView view, int errorCode, String description, String failingUrl)；
         * API 23之后回调onReceivedError(WebView view, WebResourceRequest request, WebResourceError error)方法，
         * 在开发的应用程序中，最好同时重写上面两个错误处理的方法，兼容不同API版本，防止设置无效。
         * @param view
         * @param request
         * @param error
         */
        @Override
        public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
            super.onReceivedError(view, request, error);
            loadWebByDataWithBaseURL("<html></html>");
            loadErrorLayout.setVisibility(View.VISIBLE);
        }

        @Override
        public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
            handler.proceed();
        }
    };

    protected void shouldOverrideUrlLoading(WebView view, String url) {

    }

    protected void onWebPageFinished(View view, String url) {

    }

    protected void onDestroy() {
        if (webView != null) {
            webView.getSettings().setBuiltInZoomControls(true);
        }
        super.onDestroy();
    }

    /**
     * 若存在历史记录，返回上一浏览页面
     *
     * @param keyCode
     * @param event
     * @return
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK) && webView.canGoBack()) {
            webView.goBack();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    public interface RefreshTitleListener {
        void onRefreshTitle(String title);
    }

    private RefreshTitleListener mRefreshTitleListener;

    public void setRefreshTitleListener(RefreshTitleListener refreshTitleListener) {
        mRefreshTitleListener = refreshTitleListener;
    }
}
